package com.fjp.heartguard.ui.main

import android.content.Intent
import android.os.Bundle
import android.os.Looper
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.fjp.heartguard.R
import com.fjp.heartguard.app.App
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.eventViewModel
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.app.util.AppUtils
import com.fjp.heartguard.app.util.CacheUtil
import com.fjp.heartguard.app.util.SettingUtil
import com.fjp.heartguard.databinding.ActivityMainBinding
import com.fjp.heartguard.ui.login.LoginActivity
import com.fjp.heartguard.viewmodel.MainViewModel
import com.heartguard.appupdate.utils.ApkUtils
import com.lxj.xpopup.XPopup
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.parseState

class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {
    private val tabIcons = arrayListOf(R.drawable.tab_home, R.drawable.tab_reports, R.drawable.tab_mine)
    private val tabName = arrayListOf("调查问卷", "测评档案", "我的")
    private var province = ""
    private var city = ""
    private var district = ""
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.viewPager.adapter = MainFragmentPagerAdapter(supportFragmentManager)
        mDatabind.viewPager.offscreenPageLimit = 2
        mDatabind.tabLayout.setupWithViewPager(mDatabind.viewPager)
        initTabLayout()
        location()

    }

    override fun onResume() {
        super.onResume()
        mViewModel.unreadNumbers()
        mViewModel.getQuestionnaireCount()
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.homeUnreadNumbers.observe(this) {
            parseState(it, {
                eventViewModel.unreadMessageEvent.postValue(it)
            })
        }
        mViewModel.questionnatireCount.observe(this) {
            parseState(it, {
                eventViewModel.questionnatireCountEvent.postValue(it)
            }, {
                it.printStackTrace()
            })
        }

        eventViewModel.noPermission.observeInActivity(this) {
            showLogoutPop()
        }
    }

    private fun initTabLayout() {
        tabIcons.forEachIndexed { index, _ ->
            mDatabind.tabLayout.getTabAt(index)!!.customView = getTabItemView(index)
        }
    }

    private fun getTabItemView(index: Int): View {
        val item = View.inflate(this, R.layout.tab_item, null)
        item.findViewById<TextView>(R.id.tabName).setText(tabName[index])
        item.findViewById<ImageView>(R.id.tabIcon).setBackgroundResource(tabIcons[index])
        return item
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) {
            return
        }
        if (requestCode == ApkUtils.GET_UNKNOWN_APP_SOURCES) {
            App.apkFile?.let { ApkUtils.installAPK(this, it) }

        }
    }

    private fun location() {
        TencentLocationManager.setUserAgreePrivacy(true)
        val mLocationManager = TencentLocationManager.getInstance(this)
        val request = TencentLocationRequest.create()
        request.isGpsFirst = true
        mLocationManager.requestSingleFreshLocation(request, object : TencentLocationListener {
            override fun onLocationChanged(location: TencentLocation?, error: Int, p2: String?) {
                if (error == TencentLocation.ERROR_OK && location != null && location.city != null) {
                    if (location.province != null) {
                        this@MainActivity.province = location.province
                    }
                    if (location.city != null) {
                        this@MainActivity.city = location.city
                    }

                    if (location.district != null) {
                        this@MainActivity.district = location.district
                    }
                    mViewModel.deviceAdd(AppUtils.getAppVersionName(this@MainActivity), SettingUtil.getDeviceId(this@MainActivity), this@MainActivity.province, this@MainActivity.city, this@MainActivity.district)
                }else {
                    appContext.showToast("获取定位数据失败")
                }

            }

            override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {

            }

        }, Looper.getMainLooper())

    }

    private fun showLogoutPop() {
        XPopup.Builder(this).asConfirm("提示", "您的账号已被锁定，请联系管理员解锁", "取消", "确定", {
            exit()
        }, {
            exit()
        }, false).show()
    }

    fun exit() {
        CacheUtil.setUser(null)
        val intent = Intent(appContext, LoginActivity::class.java)
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }
}
